package com.chensu.filter;


import com.alibaba.fastjson.JSON;
import com.chensu.common.BaseContext;
import com.chensu.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截所有访问请求,进行判断是否登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j

public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1=(HttpServletResponse) response;
        //1.获取本次请求是否需要处理
        String requestURI = request1.getRequestURI();
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/static/backend/**",
                "/static/front/**",
        };
        //2.判断本次请求是否处理\
        boolean check = check(urls, requestURI);
        //3.不需要处理的直接放行
        if(check){
            chain.doFilter(request1, response1);
            return;
        }
        //4.如果登录过时,直接放行
        if(request1.getSession().getAttribute("employee")!=null){
            Long empId= (Long) request1.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            chain.doFilter(request1, response1);
            return;
        }
        //5.如果为登录,跳转到登录
        response1.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截请求{}",((HttpServletRequest) request).getRequestURI());
        return;
    }

    /**
     * 定义一个check方法,来判断本次请求是否放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
